<?php
/**
 * ApiHandle.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/4/22
 * Time: 15:56
 */
namespace app\exception;

use Exception;
use think\App;
use think\Config;
use think\exception\HttpException;
use think\Request;
use think\Response;
use think\exception\Handle;

class ApiHandle extends Handle {

    /**
     * 获取常量列表
     * @return array 常量列表
     */
    private static function getConst()
    {
        return get_defined_constants(true)['user'];
    }

    /**
     * @param Exception $exception
     * @return Response
     */
    protected function convertExceptionToResponse(Exception $exception)
    {
        $request = Request::instance();
        if(!$request->isAjax())
        {
            if($exception->getCode() == 302)
            {
                return view('exception@code/302',['data'=>['code'=>302,'msg'=>$exception->getMessage()]]);
            }
            return parent::convertExceptionToResponse($exception);
        }
        // 收集异常数据
        if (App::$debug) {
            // 调试模式，获取详细的错误信息
            $data = [
                'name'    => get_class($exception),
                'file'    => $exception->getFile(),
                'line'    => $exception->getLine(),
                'msg' => $this->getMessage($exception),
                'trace'   => $exception->getTrace(),
                'code'    => $this->getCode($exception),
                'source'  => $this->getSourceCode($exception),
                'datas'   => $this->getExtendData($exception),
                'tables'  => [
                    'GET Data'              => $_GET,
                    'POST Data'             => $_POST,
                    'Files'                 => $_FILES,
                    'Cookies'               => $_COOKIE,
                    'Session'               => isset($_SESSION) ? $_SESSION : [],
                    'Server/Request Data'   => $_SERVER,
                    'Environment Variables' => $_ENV,
                    'ThinkPHP Constants'    => $this->getConst(),
                ],
            ];
        } else {
            // 部署模式仅显示 Code 和 Message
            $data = [
                'code'    => $this->getCode($exception),
                'msg' => $this->getMessage($exception),
            ];

//            if (!Config::get('show_error_msg')) {
//                // 不显示详细错误信息
//                $data['message'] = Config::get('error_message');
//            }
        }

        $response = Response::create($data, 'json');

        if ($exception instanceof HttpException) {
            $statusCode = $exception->getStatusCode();
            $response->header($exception->getHeaders());
        }

        if (!isset($statusCode)) {
            // $statusCode = 500;
            $statusCode = 200;
        }
        $response->code($statusCode);
        return $response;
    }
}
